package cn.miketsu.iced.uitl;

import cn.miketsu.iced.config.DataBase;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * JDBC工具类
 *
 * @author wangzefeng
 * @since 1.0-SNAPSHOT
 */
public class JdbcUtil {
    private static String driver;
    private static String jdbcUrl;
    private static String userName;
    private static String password;

    public static void loadConfig(DataBase dataBase) {
        if (dataBase.getDriver() == null || dataBase.getDriver().equals("")) {
            dataBase.autoConfigDriver();
        }

        driver = dataBase.getDriver();
        jdbcUrl = dataBase.getUrl();
        userName = dataBase.getUsername();
        password = dataBase.getPassword();

        try {
            Class.forName(driver);
        } catch (ClassNotFoundException var2) {
            var2.printStackTrace();
        }

    }

    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(jdbcUrl, userName, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void closeResource(Statement state, Connection conn) {
        if (state != null) {
            try {
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
